/**
* @author StevenDong/kingdeezhao@gmail.com
* @date 2021/5/20 11:17 上午
* @Description:
* @params:
*/

const compressImg = (imgUrl, el) => {
    const elWidth = el && el.width;
    const elHeight = el && el.height;
    let resize = '/resize,m_fill';
    if (elWidth) {
        resize += `,w_${elWidth}`;
    }
    if (elHeight) {
        resize += `,h_${elHeight}`;
    }
    if (!elWidth && !elHeight) {
        resize = '';
    }
    // 判断webp
    const canUseWebp = document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') === 0;
    let webp = '';
    if (canUseWebp) {
        webp = '/format,webp';
    }
    return `${imgUrl}?x-oss-process=image${resize}/auto-orient,1/quality,Q_100/bright,-1${webp}`;
};

const imgHost = {
    bind: function (el, binding) {
        const url = binding.value.url;
        setTimeout(() => {
            let dom = el.getElementsByTagName('img')[0];
            if (url && el.getElementsByTagName('img')[0]) {
                el.getElementsByTagName('img')[0].src = compressImg(url, dom);
            }
        }, 800);
    },
    update: function (el, binding) {
        const url = binding.value.url;
        setTimeout(() => {
            let dom = el.getElementsByTagName('img')[0];
            if (url) {
                el.getElementsByTagName('img')[0].src = compressImg(url, dom);
            }
        }, 800);
    }
};

export default {
    install (Vue) {
        Vue.directive('imgHost', imgHost);
    }
};
